package com.jucai.pppeiyouclient.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.adapter.OrderListAdapter;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.bean.OrderBean;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.TextCheckUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.weidget.pulltorefresh.PullToRefreshForRecyclerView;
import com.jucai.pppeiyouclient.weidget.pulltorefresh.PullToRefreshLayout;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class OrderListActivity extends BaseActivity implements PullToRefreshLayout.OnRefreshListener {

    private static final String TAG = "OrderListActivity : ";
    private static final int SELECT_CITY = 1001;
    private static final int DO_SCREEN = 1002;
    private TextView orderLocation, orderScreen;
    private EditText orderKeyWord;
    private PullToRefreshForRecyclerView orderRv;
    private PullToRefreshLayout refreshLayout;
    private List<OrderBean> orders = new ArrayList<>();
    private OrderListAdapter orderListAdapter;
    private String sexBack, ageBack, timeBack, eduBack;
    private Handler mHandler = new Handler();
    private int page = 1;
    private String city_id;
    private String keyword;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_list);

        sexBack = "";
        ageBack = "";
        timeBack = "";
        eduBack = "";
        keyword = "";
        orderListAdapter = new OrderListAdapter(OrderListActivity.this, orders);
        ((TextView) findViewById(R.id.common_title_text)).setText("接单");
        orderLocation = (TextView) findViewById(R.id.order_location);
        orderScreen = (TextView) findViewById(R.id.order_screen);
        orderKeyWord = (EditText) findViewById(R.id.order_key_word);
        refreshLayout = ((PullToRefreshLayout) findViewById(R.id.refresh_view));
        orderRv = (PullToRefreshForRecyclerView) findViewById(R.id.content_view);
        orderRv.setLayoutManager(new LinearLayoutManager(OrderListActivity.this, LinearLayoutManager.VERTICAL, false));
        orderRv.setItemAnimator(new DefaultItemAnimator());
        orderRv.setAdapter(orderListAdapter);
    }

    @Override
    protected void initData() {

        if (TextCheckUtils.isEmpty(SharedPreferencesUtil.getStringPreference(OrderListActivity.this, "PREFERENCE", "service_city", ""))) {
            orderLocation.setVisibility(View.GONE);
        } else {
            orderLocation.setVisibility(View.VISIBLE);
        }

        city_id = SharedPreferencesUtil.getStringPreference(OrderListActivity.this, "PREFERENCE", "service_city_id", "");
        orderLocation.setText(SharedPreferencesUtil.getStringPreference(OrderListActivity.this, "PREFERENCE", "service_city", ""));

        orderKeyWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyword = orderKeyWord.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        orderKeyWord.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (!TextCheckUtils.isEmpty(keyword)) {

                        HashMap<String, String> param = new HashMap<>();
                        param.put("service", "Conductor_Order.getlist");

                        param.put("page", "1");
                        param.put("keyword", keyword);


                        if (!TextUtils.isEmpty(sexBack)) {
                            param.put("sex", sexBack);
                        }

                        if (!TextUtils.isEmpty(ageBack)) {
                            param.put("minage", ageBack);
                        }

                        if (!TextUtils.isEmpty(timeBack)) {
                            param.put("start_time", timeBack);
                        }

                        if (!TextUtils.isEmpty(eduBack)) {
                            param.put("education", eduBack);
                        }

                        if (!TextUtils.isEmpty(city_id)) {
                            param.put("city", city_id);
                        }

                        CommonRequestNetData.getJsonArrayData(OrderListActivity.this, param, true, new CommonRequestNetData.JsonArrayCallBack() {
                            @Override
                            public void parseJsonArray(JSONArray jsonArray) {
                                try {
                                    LogUtils.e(TAG + "filter --> jsArr = " + jsonArray.toString());
                                    orders.clear();
                                    orders = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<OrderBean>>() {
                                    }.getType());
                                    LogUtils.e(TAG + "filter ---> orders = " + orders);
                                    orderListAdapter.setData(orders);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });

                    }
                }
                return false;
            }
        });

    }

    @Override
    protected void loadNetData() {

        HashMap<String, String> orderParam = new HashMap<>();
        orderParam.put("service", "Conductor_Order.getlist");
        orderParam.put("page", "1");

        if (!TextUtils.isEmpty(sexBack)) {
            orderParam.put("sex", sexBack);
        }

        if (!TextUtils.isEmpty(ageBack)) {
            orderParam.put("minage", ageBack);
        }

        if (!TextUtils.isEmpty(timeBack)) {
            orderParam.put("start_time", timeBack);
        }

        if (!TextUtils.isEmpty(eduBack)) {
            orderParam.put("education", eduBack);
        }

        if (!TextUtils.isEmpty(city_id)) {
            orderParam.put("city", city_id);
        }

        if (!TextUtils.isEmpty(orderKeyWord.getText().toString())) {
            orderParam.put("keyword", orderKeyWord.getText().toString());
        }

        if (!TextUtils.isEmpty(keyword)) {
            orderParam.put("keyword", keyword);
        }

        LogUtils.d(orderParam.toString());

        CommonRequestNetData.getJsonArrayData(OrderListActivity.this, orderParam, true, new CommonRequestNetData.JsonArrayCallBack() {
            @Override
            public void parseJsonArray(JSONArray jsonArray) {
                try {
                    LogUtils.e(TAG + "jsonArray = " + jsonArray.toString());
                    List<OrderBean> list = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<OrderBean>>() {
                    }.getType());
                    if (list != null && !list.isEmpty()) {
                        orders.addAll(list);
                        orderListAdapter.setData(orders);
                    } else
                        ToastUtils.showToast("没有更多数据~");

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_CITY:
                    String cityBack = data.getStringExtra("city_name");
                    city_id = data.getStringExtra("city_id");
                    if (cityBack.length() > 4) {
                        cityBack = cityBack.substring(0, 4) + "...";
                    }
                    orderLocation.setText(cityBack);
                    break;

                case DO_SCREEN:

                    sexBack = data.getStringExtra("filter_sex");
                    ageBack = data.getStringExtra("filter_age");
                    timeBack = data.getStringExtra("filter_time");
                    eduBack = data.getStringExtra("filter_edu");

                    LogUtils.d("Order 筛选条件：" + sexBack + "|" + ageBack + "|" + timeBack + "|" + eduBack);

                    HashMap<String, String> param = new HashMap<>();
                    param.put("service", "Conductor_Order.getlist");
                    param.put("page", "1");

                    if (!TextUtils.isEmpty(sexBack)) {
                        param.put("sex", sexBack);
                    }

                    if (!TextUtils.isEmpty(ageBack)) {
                        param.put("minage", ageBack);
                    }

                    if (!TextUtils.isEmpty(timeBack)) {
                        param.put("start_time", timeBack);
                    }

                    if (!TextUtils.isEmpty(eduBack)) {
                        param.put("education", eduBack);
                    }

                    if (!TextUtils.isEmpty(city_id)) {
                        param.put("city", city_id);
                    }

                    if (!TextUtils.isEmpty(keyword)) {
                        param.put("keyword", keyword);
                    }

                    CommonRequestNetData.getJsonArrayData(OrderListActivity.this, param, true, new CommonRequestNetData.JsonArrayCallBack() {
                        @Override
                        public void parseJsonArray(JSONArray jsonArray) {
                            try {
                                LogUtils.e(TAG + "filter --> jsArr = " + jsonArray.toString());
                                orders.clear();
                                List<OrderBean> list = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<OrderBean>>() {
                                }.getType());
                                if (list != null && !list.isEmpty()) {
                                    orders.addAll(list);
                                    orderListAdapter.setData(orders);
                                } else
                                    ToastUtils.showToast("没有更多数据~");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
                    break;
            }
        }
    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
        orderLocation.setOnClickListener(this);
        orderScreen.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(OrderListActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.order_location:
                //startActivityForResult(new Intent(OrderListActivity.this, CitySelectActivity.class), SELECT_CITY);
                break;

            case R.id.order_screen:
                Intent intent = new Intent();
                intent.putExtra("sex", sexBack);
                intent.putExtra("minage", ageBack);
                intent.putExtra("start_time", timeBack);
                intent.putExtra("education", eduBack);
                intent.putExtra("city", city_id);
                intent.setClass(OrderListActivity.this, OrderFilterActivity.class);
                startActivityForResult(intent, DO_SCREEN);
                break;
        }
    }

    @Override
    public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadNetData();
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }
        }, 500);
    }

    @Override
    public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
        ++page;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                HashMap<String, String> orderParam = new HashMap<>();
                orderParam.put("service", "Conductor_Order.getlist");
                orderParam.put("page", page + "");

                if (!TextUtils.isEmpty(sexBack)) {
                    orderParam.put("sex", sexBack);
                }

                if (!TextUtils.isEmpty(ageBack)) {
                    orderParam.put("minage", ageBack);
                }

                if (!TextUtils.isEmpty(timeBack)) {
                    orderParam.put("start_time", timeBack);
                }

                if (!TextUtils.isEmpty(eduBack)) {
                    orderParam.put("education", eduBack);
                }

                if (!TextUtils.isEmpty(city_id)) {
                    orderParam.put("city", city_id);
                }

                if (!TextUtils.isEmpty(keyword)) {
                    orderParam.put("keyword", keyword);
                }

                CommonRequestNetData.getJsonArrayData(OrderListActivity.this, orderParam, true, new CommonRequestNetData.JsonArrayCallBack() {
                    @Override
                    public void parseJsonArray(JSONArray jsonArray) {
                        try {
                            LogUtils.e(TAG + "jsonArray = " + jsonArray.toString());
                            List<OrderBean> list = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<OrderBean>>() {
                            }.getType());
                            if (list != null && !list.isEmpty()) {
                                orders.addAll(list);
                                orderListAdapter.setData(orders);
                            } else
                                ToastUtils.showToast("没有更多数据~");

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            }
        }, 500);

    }
}
